package logic

import (
	"bluebell_qimi/dao/mysql"
	"bluebell_qimi/models"
	"bluebell_qimi/pkg/jwt"
	"bluebell_qimi/pkg/snowflake"
)

// 存放业务逻辑的代码
func SignUp(p *models.ParamSignUp) (err error) {
	//1. 判断用户存不存在
	if err := mysql.CheckUserExist(p.Username); err != nil {
		return err
	}

	//2. 生成UID
	userID := snowflake.GenID()
	//构造user实例
	user := &models.User{
		UserID:   userID,
		Username: p.Username,
		Password: p.Password,
	}

	//3. 保存到数据库
	return mysql.InsertUser(user)
}

func Login(p *models.ParamLogin) (user *models.User, err error) {
	user = &models.User{
		Username: p.Username,
		Password: p.Password,
	}
	//传递的是指针，就能拿到user.UserID
	if err = mysql.Login(user); err != nil {
		return
	}
	//生成JWT
	token, err1 := jwt.GenToken(user.UserID, user.Username)
	if err1 != nil {
		return
	}
	user.Token = token
	//要返回login的err值，生成token不需要返回
	return
}

// 老版
//func Login(p *models.ParamLogin) (token string, err error) {
//	user := &models.User{
//		Username: p.Username,
//		Password: p.Password,
//	}
//	//传递的是指针，就能拿到user.UserID
//	if err = mysql.Login(user); err != nil {
//		return
//	}
//	//生成JWT
//	return jwt.GenToken(user.UserID, user.Username)
//}
